package ArithmeticLibrary.Util;

import Verifier.GeneralUtil;
import ArithmeticLibrary.Sets.EllipticCurve;
import ArithmeticLibrary.Sets.Group;
import ArithmeticLibrary.Sets.MultiplicativeGroup;
import ByteTree.ByteTree;
import ByteTree.Leaf;

public class Marshalling {

	/* recovered Gq from marshel(Gq) by removing the comment and colons, converting the hexadecimal string to a
	 *	byte array, converting the byte array into a byte tree, and converting the byte tree into a group Gq */
	public static Group Unmarshal(String s) throws Exception {
		
		String groupType;
		ByteTree groupBT;
		try
		{
			s = s.substring(s.indexOf("::") + 2);
			ByteTree BT = new ByteTree(GeneralUtil.hexStringToByteArray(s));
			Leaf leafPrefix = (Leaf) BT.getRoot().getChildren().get(0);
			groupType = new String(leafPrefix.getData());
			groupBT = new ByteTree(BT.getRoot().getChildren().get(1));
		} catch (Exception e) {
			throw new Exception("Unmarshal faild\n" + e);
		}
		
		if (groupType.compareTo("verificatum.arithm.ModPGroup") == 0) 
			return new MultiplicativeGroup(groupBT);
		else if (groupType.compareTo("verificatum.arithm.ECqPGroup") == 0)
				return new EllipticCurve(groupBT);
		else 
			throw new Exception("Unmarshal cannot recognize the Group name");
	}
}
